﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.IO;  // FileStream
using System.Runtime.InteropServices;
using System.Media;
using System.Threading;  // DLL

namespace TTS_mp3拼接
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string strMp3PathA = "";  // 存储路径
        string strMp3PathB = "";  // 存储路径
        string strMp3PathC = "";  // 存储路径
        string strCurrentPath = System.AppDomain.CurrentDomain.BaseDirectory;  // 基路径

        /// <summary>
        /// 选取A.mp3
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnA_Click(object sender, EventArgs e)
        {
            Stream myStream = null;
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.InitialDirectory = @"C:\Users\Simor\Desktop\mp3";  // 默认路径
                ofd.Filter = "mp3 file (*.mp3)|*.mp3|All files (*.*)|*.*";  // 筛选格式
                ofd.FilterIndex = 2;
                ofd.RestoreDirectory = true;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if ((myStream = ofd.OpenFile()) != null)
                        {
                            using (myStream)
                            {
                                // Insert code to read the stream here.
                                btnA.BackColor = System.Drawing.Color.Gold;
                                strMp3PathA = ofd.FileName;
                            }
                        }
                        else
                        {
                            btnA.BackColor = System.Drawing.Color.LightGray;
                        }
                    }
                    catch (Exception ex)
                    {
                        btnA.BackColor = System.Drawing.Color.LightGray;
                        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 选取B.mp3
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnB_Click(object sender, EventArgs e)
        {                        
            Stream myStream = null;
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.InitialDirectory = @"C:\Users\Simor\Desktop\mp3";  // 默认路径
                ofd.Filter = "mp3 file (*.mp3)|*.mp3|All files (*.*)|*.*";  // 筛选格式
                ofd.FilterIndex = 2;
                ofd.RestoreDirectory = true;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if ((myStream = ofd.OpenFile()) != null)
                        {
                            using (myStream)
                            {
                                // Insert code to read the stream here.
                                btnB.BackColor = System.Drawing.Color.Gold;
                                strMp3PathB = ofd.FileName;
                            }
                        }
                        else
                        {
                            btnB.BackColor = System.Drawing.Color.LightGray;
                        }
                    }
                    catch (Exception ex)
                    {
                        btnB.BackColor = System.Drawing.Color.LightGray;
                        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 存储C.mp3
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnC_Click(object sender, EventArgs e)
        {                                  
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.InitialDirectory = @"C:\Users\Simor\Desktop\";
                sfd.Filter = "mp3 files (*.mp3)|*.mp3|All files (*.*)|*.*";
                sfd.FilterIndex = 2;
                sfd.RestoreDirectory = true;

                if (sfd.ShowDialog() == DialogResult.OK)
                {

                    try
                    {                       
                        // Code to write the stream goes here.
                        btnC.BackColor = System.Drawing.Color.Gold;
                        strMp3PathC = sfd.FileName;                        
                    }
                    catch (Exception ex)
                    {
                        btnC.BackColor = System.Drawing.Color.LightGray;
                        MessageBox.Show("save file error! " + ex.Message);
                    }                    
                }
            }                   
        }

        /// <summary>
        /// A.mp3 和 B.mp3 合并
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMerge_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(strMp3PathA) && !string.IsNullOrEmpty(strMp3PathB))
            {
                byte[] buffer = new byte[1024 * 100];
                using (FileStream outStream = new FileStream(strMp3PathC, FileMode.OpenOrCreate))
                {
                    int readedLen = 0;
                    FileStream srcStream = null;

                    srcStream = new FileStream(strMp3PathA, FileMode.Open);
                    while ((readedLen = srcStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        outStream.Write(buffer, 0, readedLen);
                    }
                    srcStream.Close();

                    srcStream = new FileStream(strMp3PathB, FileMode.Open);
                    while ((readedLen = srcStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        outStream.Write(buffer, 0, readedLen);
                    }
                    srcStream.Close();
                    outStream.Dispose();
                }                
                MessageBox.Show("合并成功");
            }
        }


        public static uint SND_ASYNC = 0x0001; // play asynchronously
        public static uint SND_FILENAME = 0x00020000; //name is file name
        [DllImport("winmm.dll")]
        public static extern uint mciSendString(string lpstrCommand,string lpstrReturnString, uint uReturnLength, uint hWndCallback);

        #region 测试
        //[DllImport("winmm.dll")]
        //private static extern int mciSendString(string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);

        //private int syncMciResult;
        //private string syncMciCommand;
        //private Form formulario;

        //public void mciSafeCall(Form form)
        //{
        //    formulario = form;
        //    syncMciCommand = "";
        //}

        //public void mciReplacement(string Command)
        //{
        //    Form1 fm = new Form1();
        //    formulario = fm;
        //    syncMciCommand = Command;
        //    if (!string.IsNullOrEmpty(syncMciCommand))
        //    {
        //        if (formulario.InvokeRequired)
        //            formulario.Invoke(new Action(() =>
        //            {
        //                syncMciResult = mciSendString(syncMciCommand, null, 0, IntPtr.Zero);
        //            }));
        //        else
        //            syncMciResult = mciSendString(syncMciCommand, null, 0, IntPtr.Zero);

        //    }
        //} 
        #endregion

        delegate void MyDelegate();

        /// <summary>
        /// 播放mp3
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPlay_Click(object sender, EventArgs e)
        {
            //MyDelegate myDelegate = PlayMp3;
            ////myDelegate();
            ////myDelegate.BeginInvoke(new AsyncCallback(CloseMp3), null);
            //myDelegate.BeginInvoke(new AsyncCallback(CloseMp3), null);

            Thread th = new Thread(PlayMp3);
            th.IsBackground = true;
            th.Start();
        }

        /// <summary>
        /// 播放MP3
        /// </summary>
        /// <param name="strMp3Path"></param>
        public void PlayMp3()
        {
            try
            {
                if (!string.IsNullOrEmpty(strMp3PathC))
                {
                    mciSendString(@"close temp_alias", null, 0, 0);
                    //string strFile = @"open ""E:/音乐/周杰伦-东风破.mp3"" alias temp_alias";
                    string strFile = "open \"\"" + strMp3PathC + "\"\" alias temp_alias";
                    mciSendString(strFile, null, 0, 0);
                    mciSendString("play temp_alias wait", null, 0, 0);

                    mciSendString("close temp_alias", null, 0, 0);  // 关闭
                }
                else
                {
                    MessageBox.Show("播放异常，文件为空");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误", ex.Message);
            }
        }


        /// <summary>
        /// 关闭mp3
        /// </summary>
        /// <param name="result"></param>
        public void CloseMp3(IAsyncResult result)
        {
            //mciSendString("close temp_alias", null, 0, 0);
        }

        /// <summary>
        /// 合并mp3文件
        /// </summary>
        /// <param name="strFilePath"></param>
        /// <param name="charList"></param>
        public void MergeMp3(string strFilePath, char[] charList)
        {            
            if (!(charList.Length > 0))
            {
                MessageBox.Show("列表为空");
                return;
            }
            if (string.IsNullOrEmpty(strFilePath))
            {
                MessageBox.Show("请先点击3.选择存储位置");
                return;
            }
            byte[] buffer = new byte[1024 * 100];
            using (FileStream outStream = new FileStream(strFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
            {
                int readedLen = 0;
                FileStream srcStream = null;
                for (int i = 0; i < charList.Length; i++)                
                {
                    if (charList[i] == '.')
                    { charList[i] = '点'; }
                    string strMp3 = strCurrentPath + "mp3\\" + charList[i] + ".mp3";
                    srcStream = new FileStream(strMp3, FileMode.Open);
                    while ((readedLen = srcStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        outStream.Write(buffer, 0, readedLen);
                    }
                    srcStream.Close();
                }                
                outStream.Close();
                //File.Create(strFilePath).Close();                
            }
        }



        /// <summary>
        /// 数字转换为大写人民币表示
        /// </summary>
        /// <param name="strMoney"></param>        
        public string MoneyToChinese(string strCurrentDigit)
        {
            // 1. 字符串切分
            string integral = "";  // 整数部分
            string dec = "";  // 小数部分
            string[] strDigitList = strCurrentDigit.Split(new char[] { '.' });
            if (strDigitList.Length > 1)
            {
                integral = strDigitList[0];
                dec = strDigitList[1];
            }
            else
            {
                integral = strDigitList[0];
                dec = "";
            }

            // 2. 数据准备         
            string[] radices = { "", "十", "百", "千" };
            string[] bigRadices = { "", "万", "亿" };
            string[] decimals = { "角", "分" };
            string CN_DOLLAR = "元";
            string CN_SYMBOL = "";  // 人民币
            string CN_INTEGER = "整";

            string d = "";
            string outputCharacters = "";
            int zeroCount = 0;
            int p = 0;
            int quotient = 0;
            int modulus = 0;

            // 3. 整数部分
            if (integral.Length > 0)
            {
                zeroCount = 0;
                for (int i = 0; i < integral.Length; i++)
                {
                    p = integral.Length - i - 1;
                    d = integral.Substring(i, 1);
                    quotient = p / 4;
                    modulus = p % 4;
                    if (d == "0")
                    {
                        zeroCount++;
                    }
                    else
                    {
                        if (zeroCount > 0)
                        {
                            outputCharacters += "0";
                        }
                        zeroCount = 0;
                        outputCharacters += d + radices[modulus];
                    }
                    if (modulus == 0 && zeroCount < 4)
                    {
                        outputCharacters += bigRadices[quotient];
                    }
                }
                if (!string.IsNullOrEmpty(outputCharacters))
                { outputCharacters += CN_DOLLAR; }
            }
            // 4. 小数部分           
            if (dec != "")
            {
                for (int i = 0; i < dec.Length; i++)
                {
                    d = dec.Substring(i, 1);
                    if (d != "0")
                    {
                        outputCharacters += d + decimals[i];
                    }
                }
            }
            // Confirm and return the final output string:
            if (outputCharacters == "")
            {
                outputCharacters = "0" + CN_DOLLAR;
            }
            if (dec == "")
            {
                outputCharacters += CN_INTEGER;
            }
            return outputCharacters;
        }


        /// <summary>
        /// 复杂文本转换播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTxt_Click(object sender, EventArgs e)
        {
            //string str = MoneyToChinese(txt.Text);
            string str = txt.Text;

            char[] charList = str.ToCharArray();
            MergeMp3(strMp3PathC, charList);
            MessageBox.Show("合并成功");
        }

        
    }
}
